package com.lz.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.ArrayList;

/**
 * Service03+
 *
 * @date 2020/12/15 9:42
 * @author Lizhong
 */
@Service
public class Service03 {
    @Transactional
    public void method01() {
        System.out.println("com.lz.service.Service03.method01 begin");
        printf();
        boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
        ArrayList<Object> objects = new ArrayList<>();
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCompletion(int status) {
                super.afterCompletion(status);
                if (TransactionSynchronizationManager.isActualTransactionActive()) {
                    System.out.println("外层有事务！");
                }

                System.out.println("after complete：" + System.identityHashCode(objects));
                printf();
            }
        });

        System.out.println("com.lz.service.Service03.method01 end");
    }

    public void printf() {
        System.out.println("===================Service03 begin===================");
        System.out.println("实际 事务:" + TransactionSynchronizationManager.isActualTransactionActive());
        System.out.println("同步 事务:" + TransactionSynchronizationManager.isSynchronizationActive());
        System.out.println("事务名称:" + TransactionSynchronizationManager.getCurrentTransactionName());
        System.out.println("===================Service03 end===================");
    }
}
